import time
import re
import json
import urllib
import scrapy
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
import math
import base64
from urllib.parse import urlencode


class spider(BaseTaxPolicySpider):
    name = "huludao_lnshldsrmzf1"

    province: str = "辽宁省"  # 取表格
    city: str = "葫芦岛市"  # 取表格
    county: str = ""  # 取表格
    park: str = "None"  # 取表格
    source: str = "辽宁省葫芦岛市人民政府"  # 取表格 同一个来源合并
    url: str = "https://www.hld.gov.cn/zwgk/fdzdgknr/lzyj/hzg/index.html"  # 注明入口网址，以便后续排错

    def start_requests(self):
        url = "https://www.hld.gov.cn/zwgk/fdzdgknr/lzyj/hzg/index.html"

        # 设置请求头
        headers = {
            'Content-Type': 'application/json'
        }

        # 发送GET请求
        yield scrapy.Request(url=url, method='GET', headers=headers, callback=self.detail_requests)

    def detail_requests(self, response, **kwargs):
        links = response.xpath("//td[@class='bt']/a/@href").getall()  # 取链接
        pubdate_list = response.xpath("//td[@class='fbrq']/text()").getall()
        print("links", links)
        print("date_list", pubdate_list)
        if len(pubdate_list) == len(links):
            for i in range(len(pubdate_list)):
                links[i] = f"https://www.hld.gov.cn/zwgk/fdzdgknr/lzyj/hzg{links[i][1:]}"
                yield scrapy.Request(links[i], callback=self.parse_detail, meta={'pubdate': pubdate_list[i]})
        else:
            raise ("出错了")

        # 翻页逻辑
        if response.meta.get("is_next") is not False:
            pattern = r"""createPageHTML\((\d+)"""
            match = re.search(pattern, response.text)
            pages = int(match.group(1))
            if pages > 1:
                print("总页数：", pages)
                for page in range(2, pages + 1):
                    print("当前页：", page)
                    not_first_url = f"https://www.hld.gov.cn/zwgk/fdzdgknr/lzyj/hzg/index_{page - 1}.html"
                    # 设置请求头
                    headers = {
                    }

                    # 发送请求
                    yield scrapy.Request(url=not_first_url, method='GET', headers=headers,
                                         callback=self.detail_requests, meta={'is_next': False})

    def parse_list(self, response, **kwargs):
        pass

    def parse_detail(self, response, **kwargs):
        item = Item()
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['source_url'] = response.url
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        # print("item", item)
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl huludao_lnshldsrmzf1".split())
